/* eslint-disable prettier/prettier */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User } from './schemas/user.schema';


@Injectable()
export class UsersService {
  constructor(
    private jwtService: JwtService,
    @InjectModel(User.name) private userModel: Model<User>) { }

  // 注册
  async create(createUserDto: CreateUserDto) {
    const flag = await this.userModel.find({ phone: createUserDto.phone })
    if (flag.length === 0) {
      const result = await this.userModel.create(createUserDto)
      return {
        code: 200,
        msg: "恭喜，注册成功！",
        data: {}
      }
    } else {
      return {
        code: 200,
        msg: "该手机号已被注册！"
      }
    }
  }

  // 登录
  async doLogin(createUserDto: CreateUserDto) {
    const flag = await this.userModel.find({ phone: createUserDto.phone })
    const payload = {
      phone: createUserDto.phone,
    };
    if (flag.length === 0) {
      return {
        code: 200,
        msg: "该手机号未注册！",
      }
    } else if(flag[0].password===createUserDto.password) {
      return {
        code: 200,
        msg: "恭喜，登录成功！",
        data:{  accessToken: await this.jwtService.signAsync(payload, {
          secret: "2402A"
        })},
      }
    }else{
      return{
        code: 200,
        msg: "密码错误！",
      }
    }
  }

  findAll() {
    return this.userModel.find()
  }

  // findOne(id: number) {
  //   return `This action returns a #${id} user`;
  // }

  // update(id: number, updateUserDto: UpdateUserDto) {
  //   return `This action updates a #${id} user`;
  // }

  // remove(id: string) {
  //   return this.userModel.deleteOne({ _id: id })
  // }
}
